package sel.me.spring.boot245.web.config.security.handler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import sel.me.spring.boot245.web.config.security.JwtProperties;
import sel.me.spring.boot245.web.domain.login.LoginUserDto;
import sel.me.spring.boot245.web.utils.JwtTokenUtil;
import sel.me.spring.boot245.web.utils.ResultUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author shenenlu
 * @date 2021-7-28 15:05
 */
@Component
public class UserLoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    JwtProperties jwtProperties;

    /**
     * 登录成功返回结果
     * @Author youcong
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication){
        // 组装JWT
        LoginUserDto selfUserEntity =  (LoginUserDto) authentication.getPrincipal();
        String token = JwtTokenUtil.createAccessToken(selfUserEntity);
        token = jwtProperties.getTokenPrefix() + token;

        // 封装返回参数
        Map<String,Object> resultData = new HashMap<>(3);
        resultData.put("code","200");
        resultData.put("msg", "登录成功");
        resultData.put("token",token);
        ResultUtil.responseJson(response, resultData);
    }
}
